"""
Copyright © 2023 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/micropython-mini-calendar
"""
__version__ = '0.1.1'
__version_info__ = (0, 1, 1)
print('module runner version:', __version__)


from time import sleep_ms
from utils.utilities import Utilities
from utils.wifihandler import WifiHandler
from ecalendar import ECalendar

# https://gitee.com/walkline/micropython-drivers
from button import Button


CONFIG = Utilities.import_config()


class Runner(object):
	def __init__(self):
		self.__ecalendar = None

		self.__buttons = Button(
			CONFIG.KEYS.KEY_LIST,
			click_cb=self.__buttons_click_cb,
			press_cb=self.__buttons_press_cb,
			timer_id=1
		)

	def start(self):
		try:
			self.__ecalendar = ECalendar()
			self.__ecalendar.clean()

			try:
				__import__(WifiHandler.STA_CONFIG_IMPORT_NAME)
				# 显示联网动画
				self.__ecalendar.show_connecting(1)
			except ImportError:
				# 显示配网动画
				self.__ecalendar.show_connecting(0)

			if WifiHandler.STATION_CONNECTED == WifiHandler.set_sta_mode(timeout_sec=120):
				self.__ecalendar.stop()
				self.__ecalendar.start()

				while True:
					sleep_ms(1000)
			else:
				Utilities.hard_reset()
		except KeyboardInterrupt:
			if self.__ecalendar: self.__ecalendar.stop()
			if self.__buttons: self.__buttons.deinit()

	def __buttons_click_cb(self, pin):
		print(f'Key {CONFIG.KEYS.KEY_MAP[pin]} clicked')
		if not self.__ecalendar: return

		if pin == CONFIG.KEYS.KEY_1:
			pass
		elif pin == CONFIG.KEYS.KEY_2:
			pass
		elif pin == CONFIG.KEYS.KEY_BLE:
			pass
		elif pin == CONFIG.KEYS.KEY_WIFI:
			pass
		elif pin == CONFIG.KEYS.KEY_BOOT:
			pass

	def __buttons_press_cb(self, time, pin):
		print(f'Key {CONFIG.KEYS.KEY_MAP[pin]} pressed {time} ms')

		if pin in (CONFIG.KEYS.KEY_WIFI, CONFIG.KEYS.KEY_BLE):
			WifiHandler.delete_sta_config_file()
			WifiHandler.delete_ble_mode_file()

			if pin == CONFIG.KEYS.KEY_BLE:
				WifiHandler.output_ble_mode_file()

			Utilities.hard_reset()


if __name__ == '__main__':
	runner = Runner()
	runner.start()
